package com.da.core.trie;

import com.da.core.app.Handler;

import java.util.Map;
import java.util.Set;

public class RouteTrie {
    private final TrieNode root;

    public RouteTrie() {
        root = new TrieNode();
    }

    public void insert(String routePath, Handler handler) {
        String[] pathSegments = routePath.split("/");
        TrieNode current = root;
        for (String segment : pathSegments) {
            if (!segment.isEmpty()) {
                if (!current.getChildren().containsKey(segment)) {
                    current.getChildren().put(segment, new TrieNode());
                }
                current = current.getChildren().get(segment);
            }
        }
        current.setHandler(handler);
    }

    public TrieNode search(String routePath) {
        String[] pathSegments = routePath.split("/");
        TrieNode current = root;
        for (String segment : pathSegments) {
            if (!segment.isEmpty()) {
                if (!current.getChildren().containsKey(segment)) {
//                    注册参数路由
                    Map<String, TrieNode> children = current.getChildren();
                    Set<String> keySet = children.keySet();
                    for (String key : keySet) {
                        if (key.contains(":")) {
                            TrieNode node = children.get(key);
                            node.getParams().put(key.substring(1), segment);
                            return node;
                        }
                    }
                    return null;
                }
                current = current.getChildren().get(segment);
            }
        }
        return current;
    }
}
